package com.yitongmao.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.bean.UserMessageBean;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.popwindow.SelectPicPopupWindow;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.BuildConfig;
import com.yitongmao.yitmfruit.R;
import com.zhy.autolayout.AutoLinearLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import hei.permission.PermissionActivity;


public class MyPersonaldatailsActivity extends PermissionActivity {
    //请求相册
    private static final int REQUEST_PICK = 101;
    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求截图
    protected static final int TAKE_PICTURE = 1;//拍照
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 102;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    //请求访问外部存储
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    protected static Uri tempUri1;
    private AutoLinearLayout header_img_ll;
    private View inflate;
    private TextView choosePhoto;
    private TextView takePhoto;
    private TextView mQuxiao;
    private Dialog dialog;
    private ImageView header_img;
    private static String imageuri;
    private LinearLayout mNickName;//弹出昵称的dialog
    private TextView mNickName1;
    private Button mBtNickName;
    private EditText mEditText;
    private LinearLayout mGender;
    private int isSex = 1;
    private String userId;
    private Button mFinish;
    private TextView gender;
    private TextView user_name;
    private SelectPicPopupWindow menuWindow;
    private LoginHuancunBean loginHuancunBean;
    private AutoLinearLayout mRedaihuitui;
    private int loginId1;
    //调用照相机返回图片文件
    private File tempFile;
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immerSion();
        setContentView(R.layout.activity_my_personaldatails);
        Gson gson = new Gson();
        String loginId = ACache.get(MyPersonaldatailsActivity.this).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
            loginId1 = loginHuancunBean.userInfo.loginId;
            userId = String.valueOf(loginHuancunBean.userInfo.id);
        }
        initView();
        userMessage(userId);
    }

    public void show() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        inflate = LayoutInflater.from(this).inflate(R.layout.altertouxiang, null);
        //初始化控件
        choosePhoto = (TextView) inflate.findViewById(R.id.choosePhoto);
        takePhoto = (TextView) inflate.findViewById(R.id.takePhoto);
        mQuxiao = (TextView) inflate.findViewById(R.id.mQuxiao);
        /*choosePhoto.setOnClickListener(this);
        takePhoto.setOnClickListener(this);
        mQuxiao.setOnClickListener(this);*/
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
        //将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    //初始化
    private void initView() {
        mRedaihuitui = (AutoLinearLayout) findViewById(R.id.mRedaihuitui);
        mNickName = (LinearLayout) findViewById(R.id.nick_name_ll);
        mGender = (LinearLayout) findViewById(R.id.gender_ll);//选择性别
        NickNameDialog();//弹出昵称的dialog
        SelectDialog();//弹出性别的dialog
        header_img = (ImageView) findViewById(R.id.header_img);
        user_name = (TextView) findViewById(R.id.user_name);
        mNickName1 = (TextView) findViewById(R.id.nick_name);//更改昵称 //user_name
        gender = (TextView) findViewById(R.id.gender);
        header_img_ll = (AutoLinearLayout) findViewById(R.id.header_img_ll);//修改头像
        header_img_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 实例化SelectPicPopupWindow
                menuWindow = new SelectPicPopupWindow(MyPersonaldatailsActivity.this, itemsOnClick);
                // 显示窗口
                menuWindow.showAtLocation(MyPersonaldatailsActivity.this.findViewById(R.id.header_img_ll),
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
            }
        });
        mRedaihuitui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyPersonaldatailsActivity.this.finish();
            }
        });
    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {

            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.Layout_take_photo:
                    //权限判断
                    if (ContextCompat.checkSelfPermission(MyPersonaldatailsActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        //申请WRITE_EXTERNAL_STORAGE权限
                        ActivityCompat.requestPermissions(MyPersonaldatailsActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                    } else {
                        //跳转到调用系统相机
                        gotoCamera();
                    }
                    break;
                case R.id.Layout_pick_photo:
                    //权限判断
                    if (ContextCompat.checkSelfPermission(MyPersonaldatailsActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        //申请READ_EXTERNAL_STORAGE权限
                        ActivityCompat.requestPermissions(MyPersonaldatailsActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                READ_EXTERNAL_STORAGE_REQUEST_CODE);
                    } else {
                        //跳转到相册
                        gotoPhoto();
                    }
                    break;
            }
        }

    };

    //弹出选择性别dialog
    private void SelectDialog() {
        mGender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Dialog dialog = new Dialog(MyPersonaldatailsActivity.this, R.style.MyDialog);
                //设置它的contentView
                dialog.setContentView(R.layout.redio_dialog);
                dialog.setCanceledOnTouchOutside(true);//点击dialog外面消失dialog
                dialog.show();
                //找到dialog里面的控件及点击事件
                RadioButton mRadioMen = (RadioButton) dialog.getWindow().findViewById(R.id.radio_men);
                RadioButton mRadiowoMen = (RadioButton) dialog.getWindow().findViewById(R.id.radio_women);
                mFinish = (Button) dialog.getWindow().findViewById(R.id.mFinish);
                mRadioMen.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isSex = 1;
                    }
                });
                mRadiowoMen.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isSex = 2;
                    }
                });
                mFinish.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isSex == 1) {
                            gender.setText("男");
                            if (userId != null) {
                                userSexAmendUserMessage(userId, "男");
                            }
                            dialog.cancel();
                        }
                        if (isSex == 2) {
                            gender.setText("女");
                            if (userId != null) {
                                userSexAmendUserMessage(userId, "女");
                            }
                            dialog.cancel();
                        }
                    }
                });
            }
        });
    }

    //弹出昵称的dialog
    private void NickNameDialog() {
        mNickName.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final Dialog dialog = new Dialog(MyPersonaldatailsActivity.this, R.style.MyDialog);
                //设置它的contentView
                dialog.setContentView(R.layout.nickname_dialog);
                dialog.setCanceledOnTouchOutside(true);//点击dialog外面消失dialog
                dialog.show();
                //找到dialog里面的控件及点击事件
                mBtNickName = (Button) dialog.getWindow().findViewById(R.id.bt_nick_name);
                mEditText = (EditText) dialog.getWindow().findViewById(R.id.edit_text_nick_name);
                mBtNickName.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String mGain = mEditText.getText().toString();//获取输入的内容
                        if (!mGain.equals("")) {
                            mNickName1.setText(mGain);
                            userAmendUserMessage(userId, mGain);
                        } else {
                            ToastUtils.showShort(MyPersonaldatailsActivity.this, "昵称不能为空！");
                        }
                        dialog.cancel();
                    }
                });
            }
        });
    }

    // 跳转到照相机
    private void gotoCamera() {
        Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(MyPersonaldatailsActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    // 跳转到相册
    private void gotoPhoto() {
        Log.d("evan", "*****************打开图库********************");
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }

    // 检查文件是否存在
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    //沉浸式状态栏
    public void immerSion() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.BLACK);
        }
    }

    //回调
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (resultCode == RESULT_OK) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = (int) 7.5; /*图片长宽方向缩小倍数*/
                    options.inJustDecodeBounds = false;
                    File file = new File(String.valueOf(tempUri1));
                    Uri uri = Uri.fromFile(file);
                    try {
                        Bitmap map = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
                        header_img.setImageBitmap(map);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == RESULT_OK) {
                    Uri uri = intent.getData();
                    gotoClipActivity(uri);
                }
                break;
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == RESULT_OK) {
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_CROP_PHOTO:  //剪切图片返回
                if (resultCode == RESULT_OK) {
                    final Uri uri = intent.getData();
                    if (uri == null) {
                        return;
                    }
                    String realFilePath = getRealFilePath(MyPersonaldatailsActivity.this, uri);
                    uploading(realFilePath, userId);
                    String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                    Bitmap bitMap = BitmapFactory.decodeFile(cropImagePath);
                    //String image= String.valueOf((uri));
                    if (type == 1) {
                        header_img.setImageBitmap(bitMap);
                    } else {
                        header_img.setImageBitmap(bitMap);
                    }
                }
                break;

        }
    }

    //转换图片格式
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    // 打开截图界面
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.putExtra("type", type);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }

    //上传图片
    public void uploading(String file, String userId) {
        BaseService.getInstance().uploadOneFile(AppConstancts.Net.iconUrl, file, userId, new CallBackListener<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(String result) {
                Log.e("zzz", result.toString());
                ToastUtils.showShort(MyPersonaldatailsActivity.this, "成功");
            }

            @Override
            public void onFail(String result) {
                Log.e("onFail-----", "" + result);
                ToastUtils.showShort(MyPersonaldatailsActivity.this, "失败");
            }
        });
    }

    //转换图片格式
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {

        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    //得到用户信息并展示
    public void userMessage(String userId) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.userMessageUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                Log.e("zzz", "onSuccess:" + result);
                String string = (String) result;
                Gson gson = new Gson();
                UserMessageBean userMessageBean = gson.fromJson(string, UserMessageBean.class);
                if (userMessageBean.result.state.equals("1")) {
                    if (userMessageBean.user.headImage != null) {
                        Glide.with(MyPersonaldatailsActivity.this).load(userMessageBean.user.headImage).into(header_img);
                    }
                    user_name.setText(userMessageBean.user.userName);
                    mNickName1.setText(userMessageBean.user.petName);
                    gender.setText(userMessageBean.user.sex + "");
                }
            }

            @Override
            public void onFail(Object result) {
                ToastUtils.showShort(MyPersonaldatailsActivity.this, "失败");
            }
        });
    }

    //修改昵称
    public void userAmendUserMessage(String userId, String petName) {
        HashMap params = new HashMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("id", userId);
        params.put("petName", petName);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.amendUserMessageUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                Log.e("zzz", "" + result);
            }

            @Override
            public void onFail(Object result) {
                ToastUtils.showShort(MyPersonaldatailsActivity.this, "失败");
            }
        });
    }

    //修改性别
    public void userSexAmendUserMessage(String userId, String sex) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("id", userId);
        params.put("sex", sex);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.amendUserMessageUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                ToastUtils.showShort(MyPersonaldatailsActivity.this, "成功");
                Log.e("zzz", "..." + result);
            }

            @Override
            public void onFail(Object result) {
                ToastUtils.showShort(MyPersonaldatailsActivity.this, "失败");
            }
        });
    }
}

